package com.timkj.zgyd.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayUtil;
import com.timkj.zgyd.async.AsyncService;
import com.timkj.zgyd.dao.ZgydOrderDao;
import com.timkj.zgyd.dao.ZgydTelephoneDao;
import com.timkj.zgyd.dao.ZgydUserDao;
import com.timkj.zgyd.dto.CreateOrderDto;
import com.timkj.zgyd.entity.*;
import com.timkj.zgyd.service.ZgydOrderService;
import com.timkj.zgyd.utils.ResultVOUtil;
import com.timkj.zgyd.wxPay.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : liji
 * @date : 2020-09-02 01:05
 */
@Slf4j
@Service
public class ZgydOrderServiceImpl implements ZgydOrderService {
    private ZgydUserDao zgydUserDao;
    private AsyncService asyncService;
    private ZgydOrderDao zgydOrderDao;
    private ZgydTelephoneDao zgydTelephoneDao;
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Autowired
    public ZgydOrderServiceImpl(
            ZgydUserDao zgydUserDao,
            AsyncService asyncService, ZgydOrderDao zgydOrderDao,
            ZgydTelephoneDao zgydTelephoneDao) {
        this.zgydUserDao = zgydUserDao;
        this.asyncService = asyncService;
        this.zgydOrderDao = zgydOrderDao;
        this.zgydTelephoneDao = zgydTelephoneDao;
    }

    /**
     * 创建订单接口
     * @param dto
     */
    @Override
    public ResultVO createOrder(CreateOrderDto dto,HttpServletRequest request) {
        ResultVOUtil voUtil = new ResultVOUtil();
        if (dto.getOpenid().equals("null")){
            dto.setOpenid(String.valueOf(request.getSession().getAttribute("openid")));
        }
        Zgyd_order_tb orderTb = new Zgyd_order_tb();
        Zgyd_telephone_tb telephoneTb = new Zgyd_telephone_tb();
        if (zgydUserDao.SelectUserByOpenid(dto.getOpenid()) == null) {
            return voUtil.unkownError("zgyd_user_tb中没有这个openid : " + dto.getOpenid());
        }else {
            if ("可选".equals(zgydTelephoneDao.SelectTelephoneByNumber(dto.getTelephone()).getZgyd_telephone_status())){
                telephoneTb.setZgyd_telephone_openid(dto.getOpenid());
                telephoneTb.setZgyd_telephone_number(dto.getTelephone());
                telephoneTb.setZgyd_telephone_status("选中");
                zgydTelephoneDao.UpdateTelephoneStatus(telephoneTb);
                zgydTelephoneDao.UpdateTelephoneOpenid(telephoneTb);
                orderTb.setZgyd_order_user_openid(dto.getOpenid());
                orderTb.setZgyd_order_telephone(dto.getTelephone());
                long time = System.currentTimeMillis();
                orderTb.setZgyd_order_createTime(time);
                orderTb.setZgyd_order_endTime((time + 15*60*1000));
                orderTb.setZgyd_order_status("订单创建");
                String xtddh = WxPayService.generateOrderSN();
                orderTb.setZgyd_order_bh(xtddh);
                request.getSession().setAttribute("zgyd_order_bh",xtddh);
                zgydOrderDao.InsertOrder(orderTb);
                asyncService.monitorOrder(orderTb);
            }else {
                return voUtil.orderError("改手机号已被其他人选中");
            }
            return voUtil.success(orderTb);
        }
    }

    /**
     * 查看订单剩余时间
     */
    @Override
    public ResultVO searchOrder(String xtddh,String openid,HttpServletRequest request) {
        ResultVOUtil voUtil = new ResultVOUtil();
        if (openid.equals("null")){
            openid = (String.valueOf(request.getSession().getAttribute("openid")));
        }
        if (xtddh.equals("null")){
            xtddh = (String.valueOf(request.getSession().getAttribute("zgyd_order_bh")));
        }
        if (zgydUserDao.SelectUserByOpenid(openid) == null) {
            return voUtil.unkownError("zgyd_user_tb中没有这个openid : " + openid);
        }else {
            Zgyd_order_tb  orderTb = zgydOrderDao.SelectOrderByBh(xtddh);
            if (orderTb!=null){
                return voUtil.success(orderTb);
            }else {
                return voUtil.noOrderError("null");
            }
        }
    }

    /**
     * 判断当前用户是否有订单
     * @param openid
     */
    @Override
    public ResultVO isOrder(String openid, HttpServletRequest request) {
        ResultVOUtil voUtil = new ResultVOUtil();
        if (openid.equals("null")){
            openid = String.valueOf(request.getSession().getAttribute("openid"));
        }
        ArrayList<Zgyd_order_tb> tbs = zgydOrderDao.SelectOrderByOpenid(openid);
        if (zgydUserDao.SelectUserByOpenid(openid) == null) {
            return voUtil.unkownError("zgyd_user_tb中没有这个openid : " + openid);
        }else {
            if (tbs.size()==0){
                return voUtil.noOrderError(null);
            }else {
                for (Zgyd_order_tb tb : tbs){
                    if (!"订单已取消".equals(tb.getZgyd_order_status()) && !"订单超时结束".equals(tb.getZgyd_order_status())){
                        return voUtil.success(tb);
                    }
                }
            }
            return voUtil.noOrderError(null);
        }
    }

    /**
     * 判断当前用户是否填写个人信息
     */
    @Override
    public ResultVO isSubmitForm(String openid, String xtddh, HttpServletRequest request) {
        ResultVOUtil voUtil = new ResultVOUtil();
        if (openid.equals("null")){
            openid = String.valueOf(request.getSession().getAttribute("openid"));
        }
        if (xtddh.equals("null")){
            xtddh = String.valueOf(request.getSession().getAttribute("zgyd_order_bh"));
        }
        Zgyd_User_tb userTb = zgydUserDao.SelectUserByOpenid(openid);
        Zgyd_order_tb orderTb = zgydOrderDao.SelectOrderByBh(xtddh);
        Map<String,String> map = new HashMap<>();
        map.put("zgyd_user_wxOpenid",userTb.getZgyd_user_wxOpenid());
        map.put("zgyd_user_name",userTb.getZgyd_user_name());
        map.put("zgyd_user_idCard",userTb.getZgyd_user_idCard());
        map.put("zgyd_user_college",userTb.getZgyd_user_college());
        map.put("zgyd_user_grade",userTb.getZgyd_user_grade());
        map.put("zgyd_user_lxfs",userTb.getZgyd_user_lxfs());
        map.put("zgyd_order_telephone",orderTb.getZgyd_order_telephone());
        map.put("zgyd_order_status",orderTb.getZgyd_order_status());
        map.put("zgyd_order_bh",orderTb.getZgyd_order_bh());
        map.put("zgyd_order_sign",orderTb.getZgyd_order_sign());
        map.put("zgyd_user_total_fee",orderTb.getZgyd_order_total_fee());
        return voUtil.success(map);
    }

    /**
     * 用户手动取消订单
     */
    @Override
    public ResultVO deleteOrder(String openid, String xtddh,HttpServletRequest request) {
        ResultVOUtil voUtil = new ResultVOUtil();
        if (openid.equals("null")){
            openid = String.valueOf(request.getSession().getAttribute("openid"));
        }
        if (xtddh.equals("null")){
            xtddh = String.valueOf(request.getSession().getAttribute("zgyd_order_bh"));
        }
        Zgyd_order_tb orderTb = zgydOrderDao.SelectOrderByBh(xtddh);
        if (orderTb!=null){
            if (!"订单完成".equals(orderTb.getZgyd_order_status()) && !"订单超时结束".equals(orderTb.getZgyd_order_status()) && !"订单已取消".equals(orderTb.getZgyd_order_status())){
                orderTb.setZgyd_order_status("订单已取消");
                zgydOrderDao.UpdateOrder(orderTb);
                Zgyd_telephone_tb telephoneTb = new Zgyd_telephone_tb();
                telephoneTb.setZgyd_telephone_openid(openid);
                telephoneTb.setZgyd_telephone_number(orderTb.getZgyd_order_telephone());
                telephoneTb.setZgyd_telephone_status("可选");
                zgydTelephoneDao.UpdateTelephoneStatus(telephoneTb);
                telephoneTb.setZgyd_telephone_openid(null);
                zgydTelephoneDao.UpdateTelephoneOpenid(telephoneTb);
                return voUtil.success(zgydOrderDao.SelectOrderByBh(xtddh));
            }else {
                return voUtil.endOrderError(null);
            }
        }else {
            return voUtil.noOrderError(null);
        }
    }

    /**
     * 订单表单提交
     */
    @Override
    public ResultVO submitForm(String name, String idCard, String college, String grade,String lxfs,String openid,String xtddh,HttpServletRequest request) {
        ResultVOUtil voUtil = new ResultVOUtil();
        if (openid.equals("null")){
            openid = String.valueOf(request.getSession().getAttribute("openid"));
        }
        if (xtddh.equals("null")){
            xtddh = String.valueOf(request.getSession().getAttribute("zgyd_order_bh"));
        }
        Zgyd_order_tb orderTb = zgydOrderDao.SelectOrderByBh(xtddh);
        if ("订单创建".equals(orderTb.getZgyd_order_status()) ||
                "支付失败".equals(orderTb.getZgyd_order_status()) ||
                "正在支付".equals(orderTb.getZgyd_order_status())){
            Zgyd_User_tb userTb = new Zgyd_User_tb();
            userTb.setZgyd_user_wxOpenid(openid);
            userTb.setZgyd_user_name(name);
            userTb.setZgyd_user_idCard(idCard);
            userTb.setZgyd_user_college(college);
            userTb.setZgyd_user_grade(grade);
            userTb.setZgyd_user_lxfs(lxfs);
            zgydUserDao.UpdateUserName(userTb);
            zgydUserDao.UpdateUserIdCard(userTb);
            zgydUserDao.UpdateUserCollege(userTb);
            zgydUserDao.UpdateUserGrade(userTb);
            zgydUserDao.UpdateUserLxfs(userTb);
            //回写状态 正在支付
            orderTb.setZgyd_order_status("正在支付");
            zgydOrderDao.UpdateOrder(orderTb);
            Map<String,String> map = new HashMap<>();
            map.put("zgyd_user_wxOpenid",userTb.getZgyd_user_wxOpenid());
            map.put("zgyd_user_name",userTb.getZgyd_user_name());
            map.put("zgyd_user_idCard",userTb.getZgyd_user_idCard());
            map.put("zgyd_user_college",userTb.getZgyd_user_college());
            map.put("zgyd_user_grade",userTb.getZgyd_user_grade());
            map.put("zgyd_user_lxfs",userTb.getZgyd_user_lxfs());
            map.put("zgyd_order_telephone",orderTb.getZgyd_order_telephone());
            map.put("zgyd_order_status",orderTb.getZgyd_order_status());
            map.put("zgyd_order_bh",orderTb.getZgyd_order_bh());
            map.put("zgyd_order_sign",orderTb.getZgyd_order_sign());
            map.put("zgyd_user_total_fee",orderTb.getZgyd_order_total_fee());
            return voUtil.success(map);
        }else {
            return voUtil.noOrderError(null);
        }
    }


    /**
     * 修改订单状态
     */
    @Override
    public ResultVO changeOrderStatus(String openid,String xtddh,String status,HttpServletRequest request) {
        ResultVOUtil voUtil = new ResultVOUtil();
        if (openid.equals("null")){
            openid = String.valueOf(request.getSession().getAttribute("openid"));
        }
        if (xtddh.equals("null")){
            xtddh = String.valueOf(request.getSession().getAttribute("zgyd_order_bh"));
        }
        if (zgydUserDao.SelectUserByOpenid(openid) == null) {
            return voUtil.unkownError("zgyd_user_tb中没有这个openid : " + openid);
        }else{
            Zgyd_order_tb orderTb = zgydOrderDao.SelectOrderByBh(xtddh);
            if (orderTb!=null){
                orderTb.setZgyd_order_status(status);
                zgydOrderDao.UpdateOrder(orderTb);
                if (status.equals("支付成功") || status.equals("支付失败")){
                    Zgyd_User_tb userTb = new Zgyd_User_tb();
                    userTb.setZgyd_user_wxOpenid(orderTb.getZgyd_order_user_openid());
                    userTb.setZgyd_user_isPay(status);
                    zgydUserDao.UpdateUserStatus(userTb);
                }
                return voUtil.success(orderTb);
            }else {
                return voUtil.noOrderError(null);
            }
        }
    }

    /**
     * 发送模板消息
     * @param openid
     */
    @Override
    public ResultVO sendMessage(String openid,String xtddh,HttpServletRequest request) {
        ResultVOUtil voUtil = new ResultVOUtil();
        if (openid.equals("null")){
            openid = String.valueOf(request.getSession().getAttribute("openid"));;
        }
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://81.70.13.128:10001/timkj/SendByOpenid";
        ResponseEntity responseEntity = restTemplate.postForEntity(url,sendMessageJson(openid,xtddh),ArrayList.class);
        //修改订单完成
        Zgyd_order_tb orderTb = zgydOrderDao.SelectOrderByBh(xtddh);
        orderTb.setZgyd_order_status("订单完成");
        zgydOrderDao.UpdateOrder(orderTb);
        Zgyd_telephone_tb telephone_tb  = new Zgyd_telephone_tb();
        telephone_tb.setZgyd_telephone_number(orderTb.getZgyd_order_telephone());
        telephone_tb.setZgyd_telephone_openid(openid);
        telephone_tb.setZgyd_telephone_status("售出");
        zgydTelephoneDao.UpdateTelephoneStatus(telephone_tb);
        Zgyd_User_tb userTb = new Zgyd_User_tb();
        userTb.setZgyd_user_wxOpenid(openid);
        userTb.setZgyd_user_isPay("支付成功");
        userTb.setZgyd_user_isOrderSuccess("已购买");
        zgydUserDao.UpdateUserStatus(userTb);
        zgydUserDao.UpdateUserIsOrderSuccess(userTb);
        return voUtil.success(responseEntity.getBody());
    }

    /**
     * 微信支付结果通知
     * @param request
     */
    @Override
    public String getWxInform(HttpServletRequest request) {
        try {
            InputStream inputStream;
            StringBuilder sb = new StringBuilder();
            inputStream = request.getInputStream();
            String s;
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((s = in.readLine()) != null) {
                sb.append(s);
            }
            Map<String,String> wxInform = WXPayUtil.xmlToMap(sb.toString());
            if (wxInform.get("return_code").equals("SUCCESS")){
                //根据订单编号 回写支付成功
                Zgyd_order_tb orderTb = new Zgyd_order_tb();
                orderTb.setZgyd_order_bh(wxInform.get("out_trade_no"));
                orderTb.setZgyd_order_status("支付成功");
                zgydOrderDao.UpdateOrder(orderTb);
                sendMessage(wxInform.get("openid"),wxInform.get("out_trade_no"),request);
                log.info("支付返回成功");
                //回写数据库支付成功
                return "<xml>" +
                        "  <return_code><![CDATA[SUCCESS]]></return_code>" +
                        "  <return_msg><![CDATA[OK]]></return_msg>" +
                        "</xml> ";
            }
            in.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private JSONObject sendMessageJson(String openid,String xtddh){
        SimpleDateFormat dateFormat=new SimpleDateFormat("YYYY-MM-dd");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appId", "wxc66c054a1c53bc0d");
        jsonObject.put("appSecret","f51bb6c18d6e6c905743af1486cd4b11");
        ArrayList<SendMessageEntity> entities = new ArrayList<>();
        SendMessageEntity entity = new SendMessageEntity();
        entity.setTouser(openid);
        entity.setTemplate_id("7k7HW9sEqadNTKp1gxUqM2_Q5UjIigEdj1tKYMv2atc");
        entity.setUrl("http://zgyd.timkj.cn/zgyd/wxpay.html?openid=" + openid + "&xtddh=" + xtddh);
        JSONObject jsonObject1 = new JSONObject();
        JSONObject first = new JSONObject();
        first.put("value","亲爱的用户，您的订单付款成功，明细如下");
        first.put("color","#173177");
        JSONObject keyword1 = new JSONObject();
        keyword1.put("value",xtddh);
        keyword1.put("color","#173177");
        JSONObject keyword2 = new JSONObject();
        keyword2.put("value",dateFormat.format(new Date()));
        keyword2.put("color","#173177");
        JSONObject keyword3 = new JSONObject();
        keyword3.put("value","中国移动校园卡");
        keyword3.put("color","#173177");
        JSONObject keyword4 = new JSONObject();
        keyword4.put("value","0.00元");
        keyword4.put("color","#173177");
        JSONObject keyword5 = new JSONObject();
        keyword5.put("value","50.00元");
        keyword5.put("color","#173177");
        JSONObject remark = new JSONObject();
        remark.put("value","感谢您的惠顾，欢迎下次光临！");
        remark.put("color","#173177");
        jsonObject1.put("first",first);
        jsonObject1.put("keyword1",keyword1);
        jsonObject1.put("keyword2",keyword2);
        jsonObject1.put("keyword3",keyword3);
        jsonObject1.put("keyword4",keyword4);
        jsonObject1.put("keyword5",keyword5);
        jsonObject1.put("remark",remark);
        entity.setData(jsonObject1);
        entities.add(entity);
        jsonObject.put("msgData",entities);
        return jsonObject;
    }
}
